import PermTree from '@/components/PermTree'
import { fetchMenuIdsByRoleId, fetchMenuTree } from '@/services/admin/menu'
import { fetchRolePage, saveOrUpdateRole, saveRole } from '@/services/admin/role'
import { ADMIN_API, MENU } from '@/services/admin/typings'
import { ModalForm, PageContainer, ProColumns, ProFormText, ProTable } from '@ant-design/pro-components'
import { ProFormInstance } from '@ant-design/pro-form/lib'
import { useModel } from '@umijs/max'
import { useBoolean, useRequest } from 'ahooks'
import { Button, Divider, message } from 'antd'
import React, { useRef, useState } from 'react'

const SystemRole: React.FC = () => {
  const { getDictEnum } = useModel('dict')
  let { data: menuTree } = useRequest(fetchMenuTree)
  let [permKeys, setPermKeys] = useState([] as number[])

  const updateFormRef = useRef<ProFormInstance>()
  const [handleUpdateModalOpen, { set: openHandleUpdateModalChange, setTrue: openHandleUpdateModal }] =
    useBoolean(false)
  const [currentRow, setCurrentRow] = useState<ADMIN_API.RoleVO>()

  // 处理模态框开关事件
  const handleUpdateModalChange = (state: boolean) => {
    if (!state) {
      setPermKeys([])
    }
    openHandleUpdateModalChange(state)
  }
  const handleCreateButtonClick = () => {
    setCurrentRow(undefined)
    updateFormRef.current?.setFieldsValue({ id: null, role: null, role_key: null })
    openHandleUpdateModal()
  }
  const handleUpdateCommit = async (record: ADMIN_API.RoleDTO) => {
    record.permIds = permKeys
    const func = currentRow ? saveOrUpdateRole : saveRole
    const resp = await func(record)
    if (resp) {
      message.success('操作成功')
      return true
    }
    return false
  }
  const columns: ProColumns<ADMIN_API.RoleVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '角色代码',
      dataIndex: 'roleKey',
    },
    {
      title: '角色名称',
      dataIndex: 'role',
    },
    {
      title: '角色类型',
      valueEnum: getDictEnum('role_type'),
      dataIndex: 'type',
    },
    {
      title: '创建时间',
      width: '200px',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      align: 'center',
      width: '200px',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          disabled={record.type === '1'}
          onClick={() => {
            setCurrentRow(record)
            fetchMenuIdsByRoleId(record.id).then((data: number[]) => {
              setPermKeys(data)
            })
            updateFormRef.current?.setFieldsValue(record)
            openHandleUpdateModal()
          }}
        >
          修改
        </Button>,
      ],
    },
  ]

  return (
    <>
      <PageContainer>
        <ProTable
          columns={columns}
          request={fetchRolePage}
          toolbar={{
            actions: [
              <Button key="create" type="primary" onClick={handleCreateButtonClick}>
                添加
              </Button>,
            ],
          }}
        ></ProTable>
        <ModalForm
          title={currentRow ? '修改角色' : '添加角色'}
          formRef={updateFormRef}
          open={handleUpdateModalOpen}
          onOpenChange={handleUpdateModalChange}
          initialValues={currentRow}
          onFinish={handleUpdateCommit}
          width="350px"
        >
          <Divider>角色信息</Divider>
          <ProFormText label="id" name="id" hidden={currentRow === undefined} disabled={true}></ProFormText>
          <ProFormText label="角色名" name="role"></ProFormText>
          <ProFormText label="角色代码" name="roleKey"></ProFormText>
          <Divider>角色权限</Divider>
          <PermTree data={menuTree as MENU.MenuTreeVO[]} onCheck={setPermKeys} selectKeys={permKeys} />
        </ModalForm>
      </PageContainer>
    </>
  )
}

export default SystemRole
